package com.footprint.common.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import com.footprint.common.util.PrintUtil;

/**
 * HttpGet 工具类
 * @author lsj
 *
 */
public class HttpGetUtil {
	
	/**
	 * @param httpClient
	 * @param uri			要获取页面的uri
	 * @return			返回获取页面		
	 */
	public static String doGet(HttpClient httpClient, String uri) {
		StringBuilder str = new StringBuilder();
		HttpGet httpget = new HttpGet(uri);
		// System.out.println(httpget.getURI());
		PrintUtil.displaySeperator();
		
		HttpResponse response;
		try {
			response = httpClient.execute(httpget);
			
			// header
//			System.out.println(response.getProtocolVersion());
//			System.out.println(response.getStatusLine().getStatusCode());
//			System.out.println(response.getStatusLine().getReasonPhrase());
//			System.out.println(response.getStatusLine().toString());
//			displaySeperator();

			// header
//			HeaderIterator it = response.headerIterator("Set-Cookie");
//
//			while (it.hasNext()) {
//			    System.out.println(it.next());
//			}
//			displaySeperator();

			// HttpEntity
			HttpEntity entity = response.getEntity();
			if (entity != null) {
			    InputStream instream = entity.getContent();
			    InputStreamReader isr = new InputStreamReader(instream, "utf-8");
			    BufferedReader br = new BufferedReader(isr);
			    String tmpLine;
			    int line = 0;
				while ((tmpLine = br.readLine()) != null && (++line < 3000)) {
					// System.out.println(begin);
					str.append(tmpLine + "\n");
				}
			    br.close();
			    isr.close();
			    instream.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str.toString();
	}
}
